package com.zhaofan.other;

import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;

public class No16 {

    @Test
    public void test(){
        int[] nums={1,1,-1,-1,3};
        int i = threeSumClosest(nums, -1);
        Assert.assertEquals(-1,i);
    }

    public int threeSumClosest(int[] nums, int target) {
        if(nums.length<3){
            return 0;
        }
        Arrays.sort(nums);
        int sum,min=10000;
        for (int a = 0; a < nums.length; a++) {
            if(a>0&&nums[a-1]==nums[a]) continue;
            for(int b=a+1,c=nums.length-1;c>b;){
                sum=nums[a]+nums[b]+nums[c];
                if(min==target) return min;
                if(Math.abs(sum-target)<Math.abs(min-target)){
                    min=sum;
                }
                if(sum>target){
                    int c0=c-1;
                    while(c0>b&&nums[c0]==nums[c]){
                        c0--;
                    }
                    c=c0;
                }else {
                    int b0=b+1;
                    while(b0<c&&nums[b0]==nums[b]){
                        ++b0;
                    }
                    b=b0;
                }
            }
        }
        return min;
    }
}
